var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    open = require('open'),
    rename = require('gulp-rename'),
    htmlImport = require('gulp-html-import'),
    babel = require("gulp-babel"),
	// rjs = require('gulp-requirejs'),
    // optimize = require('gulp-requirejs-optimize')
    app = {
	  srcPath:'src/',
	  devPath:'build/',
	  prdPath:'dist/'
    };

gulp.task('lib',function(){
	gulp.src('bower_components/**/*')
		.pipe(gulp.dest(app.devPath + 'js/vendor'))
		.pipe(gulp.dest(app.prdPath + 'js/vendor'))
        .pipe($.connect.reload())
    gulp.src(app.srcPath + 'script/lib/**/*.js')
		.pipe(gulp.dest(app.devPath + 'js/lib/'))
		.pipe(gulp.dest(app.prdPath + 'js/lib/'))
		.pipe($.connect.reload())
});

gulp.task('html',function () {
    gulp.src(app.srcPath + 'html/*.html')
        .pipe(htmlImport(app.srcPath+'html/components/'))
        .pipe(gulp.dest(app.devPath))
        .pipe(gulp.dest(app.prdPath))
        .pipe($.connect.reload())
});

gulp.task('json',function(){
	gulp.src(app.srcPath + 'data/**/*')
		.pipe(gulp.dest(app.devPath + 'data'))
		.pipe(gulp.dest(app.prdPath + 'data'))
        .pipe($.connect.reload())
});

gulp.task('less',function(){
    gulp.src(app.srcPath + 'style/index.less')
        .pipe($.plumber())
		.pipe($.less())
        .pipe(gulp.dest(app.devPath + 'css'))
        .pipe($.cssmin())
        .pipe(gulp.dest(app.prdPath + 'css'))
        .pipe($.connect.reload())
});

gulp.task('js',function () {
    gulp.src(app.srcPath + 'script/app/**/*.js')
        .pipe($.plumber())
        .pipe(babel())
      // .pipe($.concat('index.js'))
        .pipe(gulp.dest(app.devPath + 'js'))
        .pipe($.uglify())
        //.pipe(rename("index.min.js"))
        .pipe(gulp.dest(app.prdPath + 'js'))
        .pipe($.connect.reload())
});

gulp.task('images',function () {
    gulp.src(app.srcPath + 'images/**/*')
        .pipe(gulp.dest(app.devPath + 'images'))
        .pipe($.imagemin())
        .pipe(gulp.dest(app.prdPath + 'images'))
        .pipe($.connect.reload())
});



gulp.task('build',['lib','html','json','less','js','images']);

gulp.task('clean',function () {
    gulp.src([app.devPath,app.prdPath])
        .pipe($.clean());
});

gulp.task('server',['build'],function () {
	$.connect.server({
		root:[app.devPath],
		livereload:true,
		port:1236
	});

	open('http://localhost:1236');

    gulp.watch('bower_components/**/*.js',['lib']);
    gulp.watch(app.srcPath + 'script/**/*.js',['lib']);
    gulp.watch(app.srcPath + '**/*.html',['html']);
    gulp.watch(app.srcPath + 'data/**/*.json',['json']);
    gulp.watch(app.srcPath + 'style/**/*.less',['less']);
    gulp.watch(app.srcPath + 'script/**/*.js',['js']);
    gulp.watch(app.srcPath + 'images/**/*',['images']);
});



gulp.task('default',['server']);
